package com.palm.hubo2o.network;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.palm.hubo2o.util.AppConfig;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by wongqi on 16/6/7.
 */
public class PalmRetrofit {
    private final static Object lock = new Object();
    private static PalmRetrofit instance;
    private final ApiService mApiService;

    private PalmRetrofit() {
        HttpUrl url = new HttpUrl.Builder().scheme(AppConfig.scheme).host(AppConfig.host).addPathSegment(AppConfig.path).addPathSegment("").build();
//        Gson gson = new GsonBuilder().setDateFormat("YYYYddHHmmss").create();
        GsonBuilder builder = new GsonBuilder();
        // Register an adapter to manage the date types as long values
        builder.excludeFieldsWithoutExposeAnnotation()
                .registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                        return new Date(json.getAsJsonPrimitive().getAsLong());
                    }
                });
        OkHttpClient client = new OkHttpClient.Builder().readTimeout(15, TimeUnit.SECONDS).addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)).build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(builder.create()))
                .build();
        mApiService = retrofit.create(ApiService.class);
    }

    public static PalmRetrofit getInstance() {
        synchronized (lock) {
            if (instance == null)
                instance = new PalmRetrofit();
            return instance;
        }
    }

    public ApiService getApi() {
        return mApiService;
    }
}
